<script setup lang="ts">
import axios from 'axios'
import { onMounted, ref } from 'vue'
import { RecycleScroller } from 'vue-virtual-scroller'
import 'vue-virtual-scroller/dist/vue-virtual-scroller.css'

type Item = {
  id: number
  name: string
}

// 所有的数据，比如这个数组存放了十万条数据
const allListData = ref<Item[]>([])

// 获取十万条数据
const getData = async () => {
  const res = await axios.get('http://localhost:3000/large-data')
  allListData.value = res.data.data
}

// 初始化加载
onMounted(() => {
  getData()
})

// 每一项的高度，比如 40 像素
const itemHeight = ref(40)
</script>

<template>
  <h2>虚拟列表-vue-virtual-scroller实现</h2>
  <RecycleScroller
    class="viewport"
    :items="allListData"
    :item-size="itemHeight"
    key-field="id"
    v-slot="{ item }"
    item-class="item"
  >
    {{ item.name }}
  </RecycleScroller>
</template>

<style scoped lang="scss">
// 虚拟列表容器盒子
.viewport {
  box-sizing: border-box;
  width: 240px;
  height: 400px;
  border: solid 1px #000000;
  // 开启滚动条
  overflow-y: auto;
  // 开启相对定位
  position: relative;

  :deep(.item) {
    box-sizing: border-box;
    width: 100%;
    height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
    // 隔行变色
    &:nth-child(even) {
      background: #c7edcc;
    }
    &:nth-child(odd) {
      background: pink;
    }
  }
}
</style>
